package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.dto.OrdersDto;
import com.example.reggie.entity.Orders;
import com.example.reggie.entity.User;
import com.example.reggie.service.OrderService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}", orders);

        orderService.submit(orders);

        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime) throws ParseException {
        log.info("page={},pageSize={},number={},beginTime={},endTime={}",page,pageSize,number,beginTime,endTime);
        //将String转换为时间类型
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        //Page<OrdersDto> ordersDtoPage = new Page<>();
        Date begin = null;
        Date end = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        if (beginTime != null && endTime != null){
            begin = sdf.parse(beginTime);
            end = sdf.parse(endTime);
        }
            LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
            lqw.eq(number != null, Orders::getNumber, number);
            lqw.between(begin != null && end != null, Orders::getOrderTime, begin,end);
            lqw.orderByDesc(Orders::getOrderTime);
            Page<Orders> page1 = orderService.page(ordersPage, lqw);
            //BeanUtils.copyProperties(page1,ordersDtoPage,"records");
            return R.success(ordersPage);
    }

    @PutMapping
    public R<String> status(@RequestBody Orders order){
        log.info("order:{}",order);
        boolean b = orderService.updateById(order);
        if (b){
            return R.success("派送成功");
        }
        return R.error("派送失败");
    }
}
